import json
import time
import traceback

from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.cache import cache
from django.core.paginator import Paginator
from django.shortcuts import render
# Create your views here.
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.views import APIView

from logsManage.views import set_server_logs
from roomManage.views import imgType_list
from tools.authToken import create_token, userAuth
from tools.encryption import getSha256, getDataAes, setDataAes
from tools.log import logger
from tools.tool import get_ip, get_json_values, get_file_type, get_time_uid, delete_file
from userManage import models
from userManage.seriallizers import UserSeriallizer, UserListSeriallizer
from Wchime import settings


class UserLogin(APIView):

    def get(self, request):
        pass
    def post(self, request):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)

            body = json.loads(request.body)
            data = get_json_values("data", body, " ")
            d = getDataAes('wchime77520', data)
            data = json.loads(d)
            username = get_json_values("username", data)
            password = get_json_values("password", data, " ")

            users = models.Loginuser.objects.filter(name=username)
            user = users.last()
            if user:
                pwd = getSha256('pwd' + password)
                if check_password(pwd, user.password):

                    seriallizer = UserSeriallizer(users, many=True)
                    now_time = time.time()
                    user_info = seriallizer.data
                    da = {'userinfo': user_info, "logintime": str(now_time)}
                    token = create_token(da, timeout=24)
                    token_time = 60 * 30
                    #
                    cache.set(str(user.id), token, token_time)

                    # set_server_logs('登录', 0, '用户登录', user.id, ip)

                    mqtt_dict = {"host": settings.mqtthost, 'port': settings.mqttwebsocket,
                                 'username': settings.mqttuser, 'password': settings.mqttpassword}

                    ret_mqtt = setDataAes('wchime77520', json.dumps(mqtt_dict))
                    print(user_info)
                    set_server_logs('用户登录', 0, '用户登录系统', user.id, ip)
                    resp = {"code": 1, "data": seriallizer.data, "token": token, 'mqtt': ret_mqtt}
                else:
                    resp = {"code": -1, "data": li, 'msg': '密码错误'}
            else:
                resp = {"code": -1, "data": li, 'msg': '用户不存在'}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
            resp = {"code": 0, "data": li, 'msg': '登录失败'}
        return Response(resp)


class UserLogout(APIView):

    @method_decorator(userAuth)
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')
            ip = get_ip(request)

            cache.delete(str(user_id))
            token = "asdfghjklz123456"

            set_server_logs('用户登出', 0, '用户退出登出', user_id, ip)
            resp = {"code": 1, "data": li, 'msg': '退出成功', 'token': token}
        except Exception as e:
            print(e)
            logger.error(traceback.format_exc())
            # print(resp)
        return Response(json.dumps(resp))

class CreateUser(APIView):
    def post(self, request):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = json.loads(request.body)
            # print(body)
            name = get_json_values("name", body)

            password = get_json_values("password1", body)
            password2 = get_json_values("password2", body)

            if password != password2:
                resp = {"code": 0, "data": li, 'msg': '两次密码不一致"'}
                return Response(json.dumps(resp))
            pwd = getSha256('pwd' + password)
            fina_pwd = make_password(pwd)

            user = models.Loginuser.objects.filter(name=name)
            if user:

                resp = {"code": 0, "data": li, 'msg': '用户已经存在'}
            else:
                item = models.Loginuser(
                    name=name,
                    password=fina_pwd,
                )
                item.save()

                resp = {"code": 1, "data": li, 'msg': '创建成功'}
        except Exception as e:
            print(e)
            logger.error(traceback.format_exc())
            # print(resp)
        return Response(json.dumps(resp))

class UserList(APIView):
    @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()
            users = models.Loginuser.objects.filter().order_by('id')

            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)

            paginator = Paginator(users, page_size)
            users = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = UserListSeriallizer(users, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'total': total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth)
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = json.loads(request.body)

            data = get_json_values("data", body, " ")
            d = getDataAes('wchime77520', data)
            data = json.loads(d)
            password = get_json_values("password", data, " ")

            pwd = getSha256('pwd' + password)
            fina_pwd = make_password(pwd)

            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')

            users = models.Loginuser.objects.filter(id=user_id).update(
                password=fina_pwd
            )
            if users:
                resp = {"code": 1, "data": li, 'msg': "修改成功"}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth)
    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            # ip = get_ip(request)
            # body = request.POST.dict()
            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')

            headhost = request.FILE.get("headhost")
            if headhost:
                file_nem, file_type = get_file_type(str(headhost))
                if file_type not in imgType_list:
                    li.append('不支持该格式')
                    resp = {"success": 0, "data": li}
                    return Response(resp)
                file_name = get_time_uid()
                filepath = '/{}/{}/{}'.format('media', 'user', file_name + file_type)
                openfile = settings.MEDIA_ROOT + '/user/' + file_name + file_type
                with open(openfile, 'wb+') as temp_file:
                    for chunk in headhost.chunks():
                        temp_file.write(chunk)
                user = models.Loginuser.objects.filter(id=user_id).last()
                if user.headshot != '/media/user/headshot.png':
                    path = settings.BASE_DIR + user.headshot
                    delete_file(path)
                user.headshot = filepath
                user.save()

                resp = {"code": 1, "data": "修改成功"}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)


class UserInfo(APIView):
    @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = request.query_params.dict()
            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')

            users = models.Loginuser.objects.filter(id=user_id)

            seriallizer = UserSeriallizer(users, many=True)
            resp = {"code": 1, "data": seriallizer.data}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth)
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            ip = get_ip(request)
            body = json.loads(request.body)
            # print(body)
            data = get_json_values("data", body, " ")
            d = getDataAes('wchime77520', data)
            data = json.loads(d)
            password0 = get_json_values("password0", data, " ")
            password1 = get_json_values("password1", data, " ")
            password2 = get_json_values("password2", data, " ")
            # print(password0, password1, password2)

            if password1 != password2:
                resp = {"code": 0, "data": li, 'msg': '两次密码不一致'}
                return Response(resp)
            pwd = getSha256('pwd' + password2)
            fina_pwd = make_password(pwd)

            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')

            user = models.Loginuser.objects.filter(id=user_id).last()

            pwd = getSha256('pwd' + password0)
            if check_password(pwd, user.password):
                user.password = fina_pwd
                user.save()

            else:
                resp = {"code": 0, "data": li, 'msg': '原密码不正确'}
                return Response(resp)

            resp = {"code": 1, "data": li, 'msg': "修改成功"}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth)
    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            # ip = get_ip(request)
            # body = request.POST.dict()
            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')

            headhost = request.FILES.get("headhost")
            # print(headhost)
            if headhost:
                file_nem, file_type = get_file_type(str(headhost))
                if file_type not in imgType_list:
                    li.append('不支持该格式')
                    resp = {"success": 0, "data": li}
                    return Response(resp)
                file_name = get_time_uid()
                filepath = '/{}/{}/{}'.format('media', 'user', file_name + file_type)
                openfile = settings.MEDIA_ROOT + '/user/' + file_name + file_type
                with open(openfile, 'wb+') as temp_file:
                    for chunk in headhost.chunks():
                        temp_file.write(chunk)
                user = models.Loginuser.objects.filter(id=user_id).last()
                if user.headshot and user.headshot != '/media/user/headshot.png':
                    path = settings.BASE_DIR + user.headshot
                    delete_file(path)
                user.headshot = filepath
                user.save()

                resp = {"code": 1, "data": "修改成功"}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)
